import { Component, Input, Output, EventEmitter, ViewChild, ElementRef, Renderer2 } from '@angular/core';
import { Color } from '../../helpers/color.class';

@Component({
    selector: 'preset',
    templateUrl: './preset.component.html',
    styleUrls: [`./preset.component.scss`]
})
export class PresetComponent {
    @Input()
    public colorPresets: Array<Color>;

    @Input()
    public hue: Color;

    @Input()
    public color: Color;

    @Output()
    public colorChange = new EventEmitter<Color>(false);

    @Output()
    public hueChange = new EventEmitter<Color>(false);

    @ViewChild('selectors')
    public selectors: ElementRef;

    constructor(public renderer: Renderer2) {}

    public onSelectionChange(color: Color, selected: ElementRef): void {
        const preSelected = this.selectors.nativeElement.querySelector('.selected');
        if (preSelected) {
            this.renderer.removeClass(preSelected, 'selected');
        }
        this.renderer.addClass(selected, 'selected');

        const selectedRgbaColor = color.getRgba();
        const selectedHsvaColor = color.getHsva();
        const newColor = new Color().setRgba(
            selectedRgbaColor.red,
            selectedRgbaColor.green,
            selectedRgbaColor.blue,
            selectedRgbaColor.alpha
        );
        const hueColor = new Color().setHsva(selectedHsvaColor.hue);
        this.hueChange.emit(hueColor);
        this.colorChange.emit(newColor);
    }
}
